<?php

namespace common\models\goods;

use Yii;
use common\models\AR;

/**
 * This is the model class for table "ecs_goods_type".
 *
 * @property integer $id
 * @property string $name
 * @property integer $enable
 */
class GoodsType extends AR {

    public $modelName = '商品类型';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%goods_type}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'enable'], 'required'],
            [['enable'], 'integer'],
            [['name'], 'unique'],
            [['name'], 'string', 'max' => 45]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '名称',
            'enable' => '启用',
            'usedAcount' => '引用次数',
        ];
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);

        //保存属性
        $post = Yii::$app->request->post();

        $mapIds = [];
        if (!empty($post['attrs'])) {
            for ($i = 0; $i < count($post['attrs']['id']); $i++) {
                $goodsTypeAttr = GoodsTypeAttr::findOne(['type_id' => $this->id, 'attr_id' => $post['attrs']['id'][$i]]);
                !$goodsTypeAttr && $goodsTypeAttr = new GoodsTypeAttr;

                $goodsTypeAttr->attributes = [
                    'type_id' => $this->id,
                    'attr_id' => $post['attrs']['id'][$i],
                    'sort_order' => intval($post['attrs']['sort'][$i]),
                    'group_name' => $post['attrs']['group'][$i],
                ];
                $goodsTypeAttr->save() && $mapIds[] = $goodsTypeAttr->id;
            }
        }

        $condition = empty($mapIds) ? 'type_id=:type_id' : ['and', 'type_id = :type_id', ['not in', 'id', $mapIds]];
        $goodsTypeAttrs = GoodsTypeAttr::find()->where($condition, [':type_id' => $this->id])->all();
        foreach ($goodsTypeAttrs as $item) {
            $item->delete();
        }
    }

    public function beforeDelete() {
        if (parent::beforeDelete()) {
            $count = GoodsTypeAttr::find()->where()->count();
            return $count == 0;
        } else {
            return false;
        }
    }

    /**
     * 获取商品类型被商品引用的次数
     * @return integer 商品类型被商品引用的次数
     */
    public function getUsedAcount() {
        return $this->hasMany(GoodsTypeAttr::className(), ['attr_id' => 'id'])->count();
    }

    /**
     * 获取商品类型下的映射关系集合
     * @return array [[GoodsTypeAttr]] 集合
     */
    public function getMaps() {
        return $this->hasMany(GoodsTypeAttr::className(), ['type_id' => 'id'])->orderBy('sort_order desc');
    }

    /**
     * 获取商品类型下，所有属性的集合,按规格和扩展属性分组
     * @return [GoodsAttr]
     */
    public function getAttrs() {
        $ret = [
            'sku' => [],
            'spec' => [],
        ];

        foreach ($this->maps as $map) {
            $goodsAttr = GoodsAttr::findOne($map->attr_id);
            if ($goodsAttr) {
                $key = $goodsAttr->type == GoodsAttr::TYPE_SKU ? 'sku' : 'spec';
                $ret[$key][] = $goodsAttr;
            }
        }

        return $ret;
    }

}
